package com.af.monitorModule.handler;

import com.af.monitorModule.common.util.TokenUtil;
import com.af.monitorModule.generator.entity.Record;
import com.af.monitorModule.generator.service.RecordService;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

@Component
public class TokenInterceptor implements HandlerInterceptor {



    @Autowired
    private ValueOperations<String,Object> valueOperations;

    @Autowired
    private TokenUtil tokenUtil;

    @Autowired
    private RecordService recordService;
    /**
     * 进入controller层之前拦截请求
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String url = httpServletRequest.getRequestURI();
        String token = httpServletRequest.getHeader("Authorization");
        String method = httpServletRequest.getMethod();


        httpServletResponse.setContentType("text/html;charset=utf-8");
        if ( method.equals("OPTIONS")){
            return true;
        }
        //判断是否携带Token请求
        if (token == null){
            httpServletResponse.setStatus(401);
            httpServletResponse.getWriter().print("未登录，请登录后操作");
            return false;
        }
        //验证携带Token的合法性
        DecodedJWT verify = tokenUtil.verify(token);
        if (verify == null){
            httpServletResponse.setStatus(401);
            httpServletResponse.getWriter().print("请求令牌异常，阻止操作，请登录后操作");
            return false;
        }
        //将操作用户的ID
        Integer userId = verify.getClaim("userId").asInt();
        Object userToken = valueOperations.get(userId.toString());
        if (userToken == null){
            httpServletResponse.setStatus(401);
            httpServletResponse.getWriter().print("无有效令牌，请重新登录");
            return false;
        }
        String real = userToken.toString();
        DecodedJWT redisVerify = tokenUtil.verify(real);
        if (redisVerify == null){
            httpServletResponse.setStatus(401);
            httpServletResponse.getWriter().print("真实令牌异常，请重新登录");
            return false;
        }
        if (! real.equals(token)){
            httpServletResponse.setStatus(401);
            httpServletResponse.getWriter().print("异地登陆，请重新登录");
            return false;
        }

        if ( !method.equals("GET") && !url.equals("/user/getTree")){
            new Thread(()->{
                Record record = new Record().setOperationTime(LocalDateTime.now()).setOperationUrl(url).setUserId(userId).setUserName(verify.getClaim("userLoginName").asString());
                recordService.save(record);
            }).start();
        }
        return  true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }

}